package com.app.project;

import java.io.File;
import java.sql.ResultSet;

import com.app.DB.Customers;
import com.app.DB.SegwayDetails;
import com.app.project.BESM_MainForUser.SelectServiceFromServer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore.Files;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class BESM_LoginActivity extends Activity{
	
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	private ProgressDialog mProgressDialog;
	private Boolean CheckLogin = false;
	private Boolean InsertService = false;
	
	private Handler mHandler = new Handler();
	private AlertDialog loginDialog;
	private AlertDialog showloginDialog;
	BESM_CheckOnline CheckInternet = new BESM_CheckOnline();
	Connect con = new Connect(); 
	ResultSet rs;
	private String    OID
					,PacketName
					,CustomerName
					,CustomerTimeCount;
	
	private String mDeviceName = "";
	private String address = "";
	private static final int TAKE_PICTURE = 100;
	private static final int SELECT_BLURTOOTH = 101;
	private Boolean camera = false;
	private Boolean ADMIN = false;
	private Bitmap camera_take = null;
	private Animation shake;
	EditText Password;
	View imagebutton_bluetooth;
	View imagebutton_camera;
	Intent User;
	Intent Admin;
	BESM_CheckOnline Net = new BESM_CheckOnline();
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.logo_bg);
		shake = AnimationUtils.loadAnimation(this, R.anim.shake);
		
		User = new Intent(BESM_LoginActivity.this,BESM_MainForUser.class);
		Admin = new Intent(BESM_LoginActivity.this,BESM_MainForAdmin.class);
		
		LayoutInflater inflater = BESM_LoginActivity.this.getLayoutInflater();
		
        loginDialog = new AlertDialog.Builder(BESM_LoginActivity.this)
        .setView(inflater.inflate(R.layout.activity_login, null))
        .setPositiveButton("OK", new DialogInterface.OnClickListener(){
        	@Override
        	public void onClick(DialogInterface dialog,int which){
        		
        	}
        }).setNegativeButton("Cancle", new DialogInterface.OnClickListener(){
        	@Override
        	public void onClick(DialogInterface dialog,int which){
        		
        	}
        }).create();
        
        showloginDialog = new AlertDialog.Builder(BESM_LoginActivity.this)
        .setView(inflater.inflate(R.layout.activity_showlogin, null))
        .setTitle("Well Come")
        .setIcon(R.drawable.logouser)
        .setPositiveButton("OK", new DialogInterface.OnClickListener(){
        	@Override
        	public void onClick(DialogInterface dialog,int which){
        		
        	}
        }).create();
        
        loginDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			
			@Override
			public void onShow(DialogInterface dialog) {
				Password = (EditText) loginDialog.findViewById(R.id.A_Login_Password);
				final InputMethodManager imm = (InputMethodManager)getSystemService(
					      Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(Password.getWindowToken(), 0);
				
				mHandler.removeCallbacks(LED_Internet);
				mHandler.postDelayed(LED_Internet, 1000);
				mHandler.removeCallbacks(LED_Bluetooth);
				mHandler.postDelayed(LED_Bluetooth, 1000);
				// TODO Auto-generated method stub
				Button button_OK = loginDialog.getButton(AlertDialog.BUTTON_POSITIVE);
				Button button_Cancle = loginDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
				imagebutton_bluetooth = loginDialog.findViewById(R.id.A_login_Imagebutton);
				imagebutton_camera = loginDialog.findViewById(R.id.A_login_Imagecamera);
				button_OK.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						imm.hideSoftInputFromWindow(Password.getWindowToken(), 0);
						// TODO Auto-generated method stub\
						Check_Internet();
						new  Loading().execute();
						
					}
					
				});
				button_Cancle.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
		                onBackPressed();
					}
					
				});
				
				imagebutton_bluetooth.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Check_Internet();
						// TODO Auto-generated method stub
						Intent newActivity = new Intent(BESM_LoginActivity.this,BESM_BluetoothConnect.class);
						startActivityForResult(newActivity,SELECT_BLURTOOTH);
					}
					
				});
				
				imagebutton_camera.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		                startActivityForResult(intent, TAKE_PICTURE); 
					}
					
				});
				
			}
		});
        
        
        
        loginDialog.show();
    
        showloginDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			
			@Override
			public void onShow(DialogInterface dialog) {
				
				Button button_OK = showloginDialog.getButton(AlertDialog.BUTTON_POSITIVE);
				final View imageview_user = showloginDialog.findViewById(R.id.A_Main_imageuser);
				TextView text_username = (TextView) showloginDialog.findViewById(R.id.A_Showlogin_username);
				TextView text_carid = (TextView) showloginDialog.findViewById(R.id.A_Showlogin_carid);
				TextView text_packettime = (TextView) showloginDialog.findViewById(R.id.A_Showlogin_packettime);
				TextView text_timeleft = (TextView) showloginDialog.findViewById(R.id.A_Showlogin_timeleft);
				
				if(camera_take!=null){
					((ImageView) imageview_user).setImageBitmap(camera_take);
				}
    			 
				if(ADMIN){
					text_username.setText("Admin");
					text_carid.setText("Admin");
					text_packettime.setText("Admin");
					text_timeleft.setText("Admin");
				}else{
					text_username.setText(CustomerName);
					text_carid.setText(mDeviceName);
					text_packettime.setText(PacketName);
					text_timeleft.setText(CustomerTimeCount);
				}
				
				text_username.setTextColor(Color.BLUE);
				text_carid.setTextColor(Color.BLUE);
				text_packettime.setTextColor(Color.BLUE);
				text_timeleft.setTextColor(Color.BLUE);
				//Login.putExtra("ServiceOID", OID);
				
				button_OK.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if(ADMIN){
							startActivity(Admin);
							finish();
						}else{
							new  InsertService().execute();
						}
						
					}
					
				});
				
			}
		});

	}
	
    protected void  onActivityResult(int requestCode,int resultCode,Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		EditText Carid = (EditText) loginDialog.findViewById(R.id.A_Login_SegwayID);
		ImageView select = (ImageView) loginDialog.findViewById(R.id.imageView4);
		
		switch (requestCode) {
		case SELECT_BLURTOOTH:
			if(resultCode==RESULT_OK){
				mDeviceName = intent.getStringExtra("Device Name");
				address = intent.getStringExtra("Device Address");
				Carid.setText(mDeviceName);
				Carid.setTextColor(Color.BLUE);
				select.setImageResource(R.drawable.green);
			}
			break;
		case TAKE_PICTURE:
			if(resultCode==RESULT_OK){
				Bundle extras = intent.getExtras();
				camera_take = (Bitmap) extras.get("data");
		        camera = true;
			}
			break;
		default:
			break;
		}
	}
    
	private void  Check_Internet(){

			ImageView select = (ImageView) loginDialog.findViewById(R.id.imageView2);
			if(Net.networkSignOn()){
				select.setImageResource(R.drawable.green);
			}else{
				select.setImageResource(R.drawable.red);
				Alert_wifi();
				//restartFirstActivity();
			}
		
	}
	
	private Runnable LED_Internet = new Runnable() {
		
		public void run() {
			Check_Internet();
			ImageView select = (ImageView) loginDialog.findViewById(R.id.imageView2);
	        Animation mAnimation = new AlphaAnimation(1, 0);
	        mAnimation.setDuration(1000);
	        mAnimation.setInterpolator(new LinearInterpolator());
	        mAnimation.setRepeatCount(Animation.INFINITE);
	        mAnimation.setRepeatMode(Animation.REVERSE); 
	        select.startAnimation(mAnimation);
	       
			
		}
	};
	
	private Runnable LED_Bluetooth = new Runnable() {

		public void run() {
			ImageView select = (ImageView) loginDialog.findViewById(R.id.imageView4);
	        Animation mAnimation = new AlphaAnimation(1, 0);
	        mAnimation.setDuration(1000);
	        mAnimation.setInterpolator(new LinearInterpolator());
	        mAnimation.setRepeatCount(Animation.INFINITE);
	        mAnimation.setRepeatMode(Animation.REVERSE); 
	        select.startAnimation(mAnimation);
		}
	};
	
	public void Showlogin() {
		  
        new AlertDialog.Builder(BESM_LoginActivity.this)
        .setTitle("Internet Not Connetting")
        .setMessage("Please connect to internet to use this Application")
        .setIcon(R.drawable.notwifi)
                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                    	Check_Internet();
                    }
                }).create().show();
	}
	
	public void Alert_wifi() {
		  
        new AlertDialog.Builder(BESM_LoginActivity.this)
        .setTitle("wellcome")
        .setMessage("Please connect to internet to use this Application")
        .setIcon(R.drawable.notwifi)
                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                    	Check_Internet();
                    }
                }).create().show();
	} 
	
	 private void restartFirstActivity() {
 		Intent i = getBaseContext().getPackageManager()
 				.getLaunchIntentForPackage(getBaseContext().getPackageName());
 		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
 				| Intent.FLAG_ACTIVITY_NEW_TASK);
 		startActivity(i);
 	}
	 
	 @Override
	    protected Dialog onCreateDialog(int id) {
	        switch (id) {
	        case DIALOG_DOWNLOAD_PROGRESS:
	            mProgressDialog = new ProgressDialog(this);
	            mProgressDialog.setMessage("Loading.....");
	            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	            mProgressDialog.setCancelable(true);
	            mProgressDialog.show();
	            return mProgressDialog;
	        default:
	            return null;
	        }
	    }
	 	//-----------AsyncTask-Loading----------------------------------//
	    public class Loading extends AsyncTask<String, Void, Void> {
	        @SuppressWarnings("deprecation")
			protected void onPreExecute() {
	        	super.onPreExecute();
	        	Password = (EditText) loginDialog.findViewById(R.id.A_Login_Password);
	        	showDialog(DIALOG_DOWNLOAD_PROGRESS);
	        }
	        @Override
	        protected Void doInBackground(String... params) {
	            // TODO Auto-generated method stub
	        	Customers usr = new Customers();
		    	try{
		    		rs = usr.selectCustomers("","",Password.getText().toString());
		    		if(rs.next()){
		    			if(Password.getText().toString().equals("")){
				    		CheckLogin = false;
						}else{
							CheckLogin = true;
						}
		    			OID = rs.getString("OID");
		    			PacketName = rs.getString("PacketName");
		    			CustomerName = rs.getString("CustomerName");
		    			CustomerTimeCount = rs.getString("CustomerTimeCount");
		    		}
		    	}catch (Exception e){
		    	}
		    	if(Password.getText().toString().equals("14121412")){
		    		ADMIN = true;
		    		CheckLogin = true;
				}
	    		return null;
	        }

	        @SuppressWarnings("deprecation")
			protected void onPostExecute(Void unused) {
	            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
	            removeDialog(DIALOG_DOWNLOAD_PROGRESS);
	            
	        	
	        	if(CheckLogin){
					if(ADMIN){
						showloginDialog.show();
					}else if(mDeviceName.equals("")){
						imagebutton_bluetooth.startAnimation(shake);
//					}else if(camera==false){
//						imagebutton_camera.startAnimation(shake);
					}else{
						showloginDialog.show();
					}
					
				}else{
					Check_Internet();
	        		Password.startAnimation(shake);
	    	    	Password.setText("");
				}
	        }
	        
	    }
	    
	  //-----------InsertService-Loading----------------------------------//
	    public class InsertService extends AsyncTask<String, Void, Void> {
	        @SuppressWarnings("deprecation")
			protected void onPreExecute() {
	        	super.onPreExecute();
	        	showDialog(DIALOG_DOWNLOAD_PROGRESS);
	        	Check_Internet();
	        }
	        @Override
	        protected Void doInBackground(String... params) {
	            // TODO Auto-generated method stub
	        	
	        	SegwayDetails usr = new SegwayDetails(
	        			null,
	        			CustomerName,
	    				"1",
	    				null,
	    				
	    				mDeviceName,	
	    				CustomerTimeCount,
	    				"Ready",
	    				null,
	    				null,
	    				CustomerName,
	    				
	    				null,
	    				"0",
	    				null,
	    				null
	    		);
	    		try {
					if(usr.OperationData("Insert") != null){
						InsertService = true;
						SegwayDetails usr2 = new SegwayDetails();
				    	try{
				    		rs = usr2.selectSegwayDetails("", CustomerName);
				    		if(rs.next()){
				    			CheckLogin = true;
				    			OID = rs.getString("OID");
				    		}
				    	}catch (Exception e){
			            	Check_Internet();
				    	}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    		
	    		return null;
	        }

	        @SuppressWarnings("deprecation")
			protected void onPostExecute(Void unused) {
	            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
	            removeDialog(DIALOG_DOWNLOAD_PROGRESS);
	            if(InsertService){
	            	User.putExtra("Device Name", mDeviceName);
	            	User.putExtra("Device Address", address);
	            	User.putExtra("OID", OID);
	            	User.putExtra("Pic", camera_take);
	            	User.putExtra("UserName", CustomerName);
	            	User.putExtra("TimeUserCount", CustomerTimeCount);
					startActivity(User);
					finish();
	            }
	        	
	        }
	        
	    }
	    
	 
	 @Override
		public void onBackPressed() {
		  
		        new AlertDialog.Builder(this)
		        .setTitle("ออกจากโปรแกรม")
		        .setMessage("ต้องการออกจากโปรแกรม")
		                .setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {

		                    public void onClick(DialogInterface arg0, int arg1) {
		                        finish();
		                        System.exit(0);
		                    }
		                })
		                .setPositiveButton(android.R.string.no, new DialogInterface.OnClickListener() {

		                    public void onClick(DialogInterface arg0, int arg1) {
		                    	loginDialog.show();
		                    }
		                }).create().show();
		} 

	
}
